package com.example.nextstream.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.nextstream.annotations.AuthRequired;
import com.example.nextstream.models.User;
import com.example.nextstream.service.UserService;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.apache.catalina.connector.Response;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Value("${sign.key}")
    private String signKey;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        AuthRequired methodAnnotation = method.getAnnotation(AuthRequired.class);

        if (methodAnnotation !=null){
            String token = httpServletRequest.getHeader("token");
            if (token==null){
                throw new RuntimeException("token error");
            }else{
                int userId;
                try {
                    userId = Integer.parseInt(JWT.decode(token).getAudience().get(0));  // 获取 token 中的 user id

                } catch (JWTDecodeException e) {
                    throw new RuntimeException("token error");
                }
                User user = userService.getUserById(userId);
                try{
                    JWTVerifier verifier =  JWT.require(Algorithm.HMAC256(signKey)).acceptExpiresAt(60*60*24*30).build();//acceptExpiresAt(2 * 60 * 60).acceptExpiresAt(3 * 60)
                try {
                    verifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new RuntimeException("token error");
                }}catch (Exception e){
                    throw new RuntimeException("token error");
                }
                httpServletRequest.setAttribute("currentUser", user);
            }
            return true;
        }


        return true;

    }
}
